package com.example.unisys.task;

import com.example.unisys.common.property.UnisysProperty;
import com.example.unisys.utils.DateUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.smattme.MysqlExportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service("asyncService")
public class BackupSqlTask {

    @Autowired
    UnisysProperty unisysProperty;
    @Autowired
    ObjectMapper objectMapper;

    //每个周天两点开启备份
    @Scheduled(cron = "0 0 2 ? * sun")
    public void WeeklyBackup() {
        log.info("开始每周备份 时间：" + DateUtil.getCurrentTime());
        try {
            Properties properties = new Properties();
            properties.putAll(objectMapper.convertValue(unisysProperty.getBackup(),
                    new TypeReference<Map<String, String>>() {
                    }));
            MysqlExportService mysqlExportService = new MysqlExportService(properties);
            mysqlExportService.export();
        } catch (Exception e) {
            log.error("任务失败：" + e.getMessage());
        }
    }

    //每个月末1点开启备份
    @Scheduled(cron = "0 0 1 28-31 * ?")
    public void MonthlyBackup() {
        final Calendar c = Calendar.getInstance();
        if (c.get(Calendar.DATE) == c.getActualMaximum(Calendar.DATE)) {
            // do your stuff
            log.info("开始每月备份 时间:" + DateUtil.getCurrentTime());
            try {
                Properties properties = new Properties();
                properties.putAll(objectMapper.convertValue(unisysProperty.getBackup(),
                        new TypeReference<Map<String, String>>() {
                        }));
                properties.setProperty("TEMP_DIR", "/root/sites/backup/month/");
                MysqlExportService mysqlExportService = new MysqlExportService(properties);
                mysqlExportService.export();
            } catch (Exception e) {
                log.error("任务失败：" + e.getMessage());
            }
        }

    }

    //日志备份定期清除 每周6 凌晨4点
    @Scheduled(cron = "0 0 4 ? * SAT")
    public void removeRedundant() {
        log.info("开始冗余数据清除 时间：" + DateUtil.getCurrentTime());
        long purgeTime = System.currentTimeMillis() - (14 * 24 * 60 * 60 * 1000);
        File dir = new File(unisysProperty.getBackup().getTEMP_DIR());
        try {
            Arrays.stream(dir.listFiles()).forEach(file -> {
                if (file.lastModified() < purgeTime)
                    if (!file.delete()) log.error("无法删除该文件 :" + file.getName());
                    else log.info("删除文件 :" + file.getName());
            });
        } catch (Exception e) {
            log.error("删除数据出错 时间：" + DateUtil.getCurrentTime());
        }

    }
}
